package vertx;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;

/**
 * @author 今何许
 * @date 2021-01-11 14:18
 */
public class UrlParamsVerticle extends AbstractVerticle {
  @Override
  public void start(Promise<Void> startPromise) throws Exception {
    // Create a Router
    Router router = Router.router(vertx);

    //http://localhost:8888/hello?id=1&name=Tom
    router.route("/hello").handler(req -> {
      String id = req.request().getParam("id");
      String name = req.request().getParam("name");
      req.response()
        .putHeader("content-type", "text/plain")
        .end(new JsonObject().put("id", id).put("name", name).toString());
    });

    //rest风格：http://localhost:8888/rest/1/Tom
    router.route("/rest/:id/:name").handler(req -> {
      String id = req.request().getParam("id");
      String name = req.request().getParam("name");
      req.response()
        .putHeader("content-type", "text/plain")
        .end(new JsonObject().put("id", id).put("name", name).toString());
    });

    //绑定路由
    vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
      if (http.succeeded()) {
        startPromise.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startPromise.fail(http.cause());
      }
    });
  }
}
